package com.kaesar.leetcode.LeetCode_051_100;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class LeetCode_055 {
    public static boolean canJump(int[] nums) {
        if (nums.length == 1) {
            return true;
        }
        if (nums[0] == 0) {
            return false;
        }
        int length = nums.length - 1;
        // 定义走到过的位置
        Set<Integer> jumped = new HashSet<>();
        jumped.add(0);
        // 定义当前到的位置
        Queue<Integer> toJump = new LinkedList<>();
        toJump.add(0);
        while (!toJump.isEmpty()) {
            Integer cur = toJump.poll();
            jumped.add(cur);
            if (nums[cur] == 0) {
                continue;
            }
            if (nums[cur] >= length - cur) {
                return true;
            } else {
                for (int i = nums[cur]; i >= 1; i--) {
                    if (!jumped.contains(cur + i) && !toJump.contains(cur + i)) {
                        toJump.add(cur + i);
                    }
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 3, 1, 1, 4};
        System.out.println(canJump(nums));
    }
}
